<template>
  <div>
    <!-- 统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6" v-for="(value, key) in stats" :key="key">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">{{ titles[key] }}</div>
          <div class="stat-value">{{ value }}</div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 冷库剩余容量排行 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <div class="chart-title">冷库剩余容量排行</div>
          <div ref="storageChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>


    <!-- 河南省地图 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card shadow="hover" class="map-card">
          <div class="chart-title">河南省仓库分布</div>
          <div ref="henanMap" class="map-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单趋势 & 异常统计 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div class="chart-title">订单趋势</div>
          <div ref="orderChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div class="chart-title">异常信息统计</div>
          <div ref="exceptionChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script>

import * as echarts from 'echarts';
import henanGeoJson from '@/assets/henan.json'; // 引入河南省地图 JSON 数据
import cityGeoJson from '@/assets/cityMap.json'; // 假设这是市级地图的 geoJson 数据
import {getlistdata, getlistdate, getlist, getStorageList, getStorageAdress} from '@/api/index';

export default {
  data() {
    return {
      orderChart: null,  // 存储折线图的实例
      exceptionChart: null, // 存储饼图的实例
      storageChart: null,  // 新增柱状图实例
      timer: null, // 定时器
      alarmTypeMap: {       // 设备类型字典
        "0": "温度异常",
        "1": "运输延误",
        "2": "设备故障"
      },     // 设备类型字典
      stats: {},
      titles: {},
      cityData: [
        // { name: "周口市", value: [114.649653, 33.620357] },
        // { name: "驻马店市", value: [114.028470, 32.983158] }
      ]
    };
  },
  mounted() {
    this.initCharts();
    this.$nextTick(() => {
      this.initMap(); // 等待 DOM 渲染后再初始化地图
    });
    // // **每 5 秒获取最新 Redis 数据**
    // this.timer = setInterval(() => {
    //   this.getStorageData();
    // }, 5000);
    // beforeDestroy(){
    //   // 清除定时器，避免内存泄漏
    //   clearInterval(this.timer);
    // };
    getlistdata().then(response => {
      this.stats = response.stats;  // 获取 stats 数据
      this.titles = response.titles;  // 获取 titles 数据
    });
    this.getStatisticsData();  // 获取统计数据
    this.getbinData();
    this.getStorageData(); // 获取冷库排行数据
    this.getStorageAdress();
    // 连接 WebSocket
    const socket = new WebSocket("ws://192.168.149.73:9888/ws");
    socket.onopen = function () {
      console.log("WebSocket 连接成功！");
    };
    socket.onmessage = function (event) {
      console.log("收到消息: " + event.data);
      this.getStorageData();  // 这里的 `this` 需要绑定
    }.bind(this);  // 手动绑定 `this` 为 Vue 实例

  },
  methods: {
    initCharts() {
      // 初始化折线图
      this.orderChart = echarts.init(this.$refs.orderChart);
      const option = {
        title: { left: 'center', textStyle: { fontSize: 16 } },
        grid: { left: '10%', right: '10%', bottom: '10%' },
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          axisLabel: { color: '#666' }
        },
        yAxis: { type: 'value', axisLabel: { color: '#666' } },
        series: [{ type: 'line', data: [], smooth: true, lineStyle: { color: '#409EFF' } }]
      };
      this.orderChart.setOption(option);

      // 初始化饼图
      this.exceptionChart = echarts.init(this.$refs.exceptionChart);
      this.exceptionChart.setOption({
        title: { left: 'center', textStyle: { fontSize: 16 } },
        tooltip: { trigger: 'item' },
        series: [{
          type: 'pie',
          radius: '60%',
          data: [
          ],
          label: { fontSize: 12 }
        }]
      });
      this.storageChart = echarts.init(this.$refs.storageChart);
      this.storageChart.setOption({
        title: { left: 'center', textStyle: { fontSize: 18 } },
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: [] },
        yAxis: { type: 'value' },
        series: [{ type: 'bar', data: [] }]
      });
    },
    getStorageAdress(){
      getStorageAdress().then(response => {
        // 判断返回值是否为数组，如果不是再尝试取 .data
        const dataArr = Array.isArray(response.data) ? response.data : response.data.data;
        this.cityData = dataArr.map(item => ({
          name: item.coldName,
          value: [item.coordinateX, item.coordinateY]
        }));

        // 如果地图已经初始化，更新地图数据
        const mapChart = echarts.getInstanceByDom(this.$refs.henanMap);
        if (mapChart) {
          mapChart.setOption({
            series: [{
              data: this.cityData
            }]
          });
        }
      }).catch(error => console.error("获取数据失败：", error));
    },
    getStorageData() {
      getStorageList().then(response => {
        if (response.code === 200 && Array.isArray(response.data)) {
          let storageData = response.data;

          // **按 totalVolume 进行降序排序**
          storageData.sort((a, b) => b.remainingVolume - a.remainingVolume);

          const names = storageData.map(item => item.coldName); // X 轴数据
          const values = storageData.map(item => item.remainingVolume); // Y 轴数据

          // 更新 ECharts 配置
          this.storageChart.setOption({
            xAxis: { data: names },
            series: [{ data: values }]
          });
        } else {
          console.error('返回数据格式异常:', response);
        }
      }).catch(error => console.error('获取冷库数据失败:', error));
    },
    getbinData() {
      getlist().then(response => {
        const Data = response.data; // 获取后端返回的数据

        // **转换数据格式**
        const pieData = Data.map(item => ({
          value: item.alarmCount,  // 后端返回的警报数量
          name: this.alarmTypeMap[item.equipmentType] || '未知异常'  // 根据设备类型映射为名称
        }));

        // **更新饼图**
        this.exceptionChart.setOption({
          series: [{
            data: pieData  // 设置饼图的数据
          }]
        });

      }).catch(error => {
        console.error('获取统计数据失败:', error);
      });
    },
    getWeekDates() {
      const now = new Date();
      const day = now.getDay();
      const diff = day === 0 ? -6 : 1 - day;
      const monday = new Date(now);
      monday.setDate(now.getDate() + diff);
      let weekDates = [];
      for (let i = 0; i < 7; i++) {
        let date = new Date(monday);
        date.setDate(monday.getDate() + i);
        weekDates.push(this.formatDate(date));
      }
      return weekDates;
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    getStatisticsData() {
      const weekDates = this.getWeekDates();
      const startDate = weekDates[0];
      const endDate = weekDates[6];

      getlistdate(startDate, endDate).then(response => {
        const resData = response.data; // 假设后端返回 { data: [0,7,1,0,0,0,0] }

        // 确保 orderChart 实例存在
        if (this.orderChart) {
          const option = this.orderChart.getOption(); // 获取当前的 option 配置
          option.series[0].data = resData; // 更新数据
          this.orderChart.setOption(option); // 更新图表
        }
      }).catch(error => {
        console.error('获取统计数据失败:', error);
      });
    },
    initMap() {
      echarts.registerMap('河南', henanGeoJson);

      const mapChart = echarts.init(this.$refs.henanMap);
      mapChart.setOption({
        title: { left: 'center', textStyle: { fontSize: 18 } },
        tooltip: { trigger: 'item' },
        geo: {
          map: '河南',
          roam: true,
          label: { show: true, color: '#000' },
          itemStyle: { areaColor: '#a2d2ff', borderColor: '#111' },
          emphasis: { itemStyle: { areaColor: '#f4a261' } }
        },
        series: [{
          type: 'scatter',
          coordinateSystem: 'geo',
          data: this.cityData,
          symbol: 'image://https://cold666.oss-cn-hangzhou.aliyuncs.com/da2842d1-6a02-44e2-9f98-448f71c7b508.png',
          symbolSize: [20, 15],
          itemStyle: { color: 'transparent' }
        }]
      });
    }
  }

};

</script>

<style scoped>
.stat-card {
  text-align: center;
  background: linear-gradient(135deg, #f3f3f3, #ffffff);
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.stat-title {
  font-size: 16px;
  color: #666;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-top: 10px;
}

.chart-card, .map-card {
  border-radius: 10px;
  padding: 15px;
}

.chart-title {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 10px;
}
.chart-container{
  height:400px;
}
.map-container {
  height: 600px;
}
</style>
